<template>
  <div class="product-page">
    <!-- 路径导航 -->

    <!-- 功能区域 -->
    <div class="filter-header">
      <el-button type="primary" @click="handleAddProduct">
        添加
      </el-button>
    </div>

    <!-- 商品列表表格 -->
    <div class="table-container">
      <el-table 
        :data="productList" 
        style="width: 100%" 
        v-loading="loading"
      >
        <el-table-column prop="productName" label="商品名称" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="product-name">{{ row.name }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="商品分类" width="160" align="center">
          <template #default="{ row }">
            <el-tag >
              {{ row.category_name }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="商品图片" width="160" align="center">
          <template #default="{ row }">
            <el-image 
              :src="row.img_path" 
              :preview-src-list="[row.img_path]"
              fit="cover"
              style="width: 100px; "

              class="product-image"
              preview-teleported
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        
        <el-table-column prop="price" label="价格" width="120" align="center">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="stock" label="库存" width="100" align="center">
          <template #default="{ row }">
            <span :class="{ 'low-stock': row.stock < 20 }">{{ row.stock }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="是否上架" width="150">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.is_shangjia" 
              @change="handleStatusChange(scope.row, 'is_shangjia')"
              :active-value="1"
              :inactive-value="2"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="操作"  fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              text
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              text
              @click="handleSetSku(scope.row)"
            >
              设置SKU
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              text
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品添加/修改对话框 -->
    <AddOrChangeProductDialog
      :product-dialog-visible="productDialogVisible"
      :edit-product-data="editProductData"
      @close-product-dialog="closeProductDialog"
      @submit-product="submitProduct"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import AddOrChangeProductDialog from '../../components/AddOrChangeProductDialog.vue'
import instance from '../../utils/request';
// 响应式数据
const loading = ref(false)
const productList = ref([])
const productDialogVisible = ref(false)
const editProductData = ref(null)

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 初始化数据
onMounted(() => {
  loadProductList()
})

// 加载商品列表
const loadProductList = async () => {
  loading.value = true
  let res = await instance.get('Goods/goodsList')
  if(res.code==200){
    productList.value = res.data
    loading.value = false
    pagination.total = productList.value.length
    
  }
}

// // 获取分类标签类型
// const getCategoryTagType = (category) => {
//   const typeMap = {
//     '电池组': 'primary',
//     '电机 ': 'success', 
//     '电池管理系统': 'warning',
//     '电机控制器': 'danger',
//     '车载充电机': 'primary',
//     'DC-DC转换器': 'success',
//     '充电桩': 'danger',
//     '充电接口': 'warning',
//     'PTC加热器':'danger',
//     '电驱动减速器':'primary'
//   }
//   return typeMap[category] || 'info'
// }



// 刷新数据
// const handleRefresh = () => {
//   loadProductList()
//   ElMessage.success('数据已刷新')
// }

// 添加商品
const handleAddProduct = () => {
  editProductData.value = null
  productDialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  editProductData.value = { ...row }
  productDialogVisible.value = true
}

// 关闭商品对话框
const closeProductDialog = () => {
  productDialogVisible.value = false
  editProductData.value = null
}

// 提交商品数据
const submitProduct = async(productData) => {
  console.log(productData,"hahahahhahah");
  
  if (productData.id) {
    // 编辑模式 - 更新现有商品
    const index = productList.value.findIndex(item => item.id === productData.id)
    if (index > -1) {
      productList.value[index] = { ...productData }
    }
  } else {
    // 新增模式 - 添加新商品
    const obj = {
      category_id:productData.category,
      name:productData.productName,
      describe:productData.description,
      img_arr:productData.carouselImages,
      img_path:productData.productImage,
      price:productData.price,
      repertory:productData.stock,
      market:productData.marketPrice,
      sales_volume:productData.virtualSales,
      content:productData.content,
      specification:[]
    }
    console.log(obj);
    
    const res = await instance.post('Goods/addGoods',obj)
    console.log(res);
    
    if(res.code==200){
      ElMessage.success("添加成功")
      loadProductList()
    }
    pagination.total = productList.value.length
  }
}

// 设置SKU
const handleSetSku = (row) => {
  ElMessage.info(`设置SKU: ${row.name}`)
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除商品 "${row.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    // 模拟删除操作
    const res = await instance.get(`Goods/deleteGoods?id=${row.id}`)
    if(res.code==200){
      ElMessage.success('删除成功')
      loadProductList()
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理状态变更
const handleStatusChange = (row, field) => {
  // const statusMap = {
  //   isOnSale: '上架状态',
  //   isHot: '热销状态',
  //   isNew: '今日上新状态',
  //   isPremium: '精品优选状态'
  // }
  
  // ElMessage.success(`${row.name} 的${statusMap[field]}已更新`)
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadProductList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadProductList()
}
</script>

<style lang="scss" scoped>
.product-page {
  .table-container {
    :deep(.el-table) {
      .el-table__header-wrapper {
        .el-table__header {
          .el-table__cell {
            justify-content: space-between;
            text-align: justify;
          }
        }
      }
      
      .el-table__body-wrapper {
        .el-table__body {
          .el-table__row {
            .el-table__cell {
              justify-content: space-between;
              text-align: justify;
            }
          }
        }
      }
    }
  }
}
</style>